//
//  OAuthViewController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/4.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit
import SVProgressHUD
import ReactiveCocoa

/// 第三方授权登录
class OAuthViewController: UIViewController, UIWebViewDelegate {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        // 替换根视图
        view = webView
        webView.delegate = self
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
    }
    
    ///  关闭控制器
    @objc private func close () {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /// 自动填充用户信息
    @objc private func autoFill () {

        /// 记得在结尾时加上分号
        let js = "document.getElementById('userId').value = '644764075@qq.com';" + "document.getElementById('passwd').value = 'qiuMING879576';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        webView.loadRequest(NSURLRequest(URL: NetWorkTools.shareNetwork.oauthUrl))
    }
    
    // MARK: UIWebViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        // 1.判断`request.url`的前半部分是否是回调地址，如果不是回调地址，继续加载
        if !urlString.hasPrefix(NetWorkTools.shareNetwork.redirectUri) {
            return true
        }
        // 2.如果是回调地址，检查query，查询字符串，判断是否包含`code=`，`query`表示`URL`中问号后面的部分，`hasPrefix`表示是否包含
        if let query = request.URL!.query where query.hasPrefix("code=")
        {
            // 3.获取请求码,截取`code=`后面的`URL`
            let code = query.substringFromIndex("code=".endIndex)
            printLog(code)
            
            // 4.调用网络方法获取Token
            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                
                printLog(error)
                
                }, completed: { () -> Void in
                SVProgressHUD.dismiss()
                
                ///  动画结束后才发送通知
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(MQSwitchRootViewController, object: "main")
                    
                })
                 
            })
 
        } else {
            
           printLog("")
        }
        
        
        return false
    }
    
    // 网络加载提示
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    // 网络加载提示
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    

}
